import Http from '@/api/http/http.js'

module.exports = {
	
	/**
	 * 发送验证码
	 * @param config
	 * @returns {*}
	 */
	sendCaptcha(phone, type){ 
		return Http.post('/api/sms', {
			anonymous:true,
			customReject: true,
			body:{
				phone,
				type
			},
		}) 
	},
	
	/**
	 * 校验验证码
	 * @param config
	 * @returns {*}
	 */
	verifyCode(phone, type, code){ 
		return Http.post('/sms/verify', {
			anonymous:true,
			customReject: true,
			body:{
				phone,
				type,
				code
			},
		}) 
	},
	
	/**
	 * 验证码登录
	 */
	smsLogin(config){ 
		config.anonymous = true;
		return Http.post('/api/login', config)
	},
	
	/**
	 * 验证码登录
	 */
	logout(){ 
		return Http.post('/api/logout')
	},
	
	
	
	/**
	 * 重置密码
	 * @param {Object} config
	 */
	resetPassword(config){
		config.anonymous = true;
		return Http.post('/password', config)
	},	
		
    /**
     * 初始化
     */
    initial: (config) => { return Http.get('/api/initial', config) },
  
    
	/**
	 * 字典
	 * @param {Object} type
	 */
	dicts(type){
		return Http.get('/system/dict/data/type/' + type);
	},	
	
	/**
	 * 上传
	 */
	upload(tempFiles){
		 
		var promises = []
		var ret = []
		
		for(var i=0; i< tempFiles.length; i++){
			let index = i
			promises.push(new Promise((resolve, reject) => {
				var reqConfig = {
					method:"POST",
					url: '/common/upload', 
					filePath: tempFiles[index].path || tempFiles[index].tempFilePath,
					name: 'file',
					success: (res) => {
						var statusCode = res.statusCode;
						if(statusCode == 200 && res.data){
							var data = JSON.parse(res.data);
							if(/^\d+$/.test(data.code)){
								statusCode = data.code;
							}
						}
						if (statusCode == 401) {
						  global.login();
						  return;
						}
						else if(statusCode == 400){
							var data = JSON.parse(res.data);
							global.toast(data.message);
							reject(res);
							return;
						}
						else if(statusCode != 200){
							var data = JSON.parse(res.data);
							global.toast(data.message||data.msg|| '上传失败');
							reject(res);
							return;
						}
						ret[index] = JSON.parse(res.data)
						resolve(ret[index])
					  },
					  fail: (err) => {
						
						reject(err)
					  }
				}
				  
				Http.combineHeaders(reqConfig);
				if (reqConfig.url.indexOf('http') !== 0) {
					reqConfig.url = global.API_BASE_PATH + reqConfig.url;
				}
				var uploadTask = uni.uploadFile(reqConfig);
				  
				uploadTask.onProgressUpdate((res) => {
					if(res.progress == 100){
						//global.hideLoading();
					}
				});
				
			}))
		}
		return Promise.all(promises)
	}
};